package com.ysstech.system.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.enums.YssCodeEnum;
import com.ysstech.common.util.verifyutil.VerifyCode;
import com.ysstech.common.util.verifyutil.VerifyCodeInfo;
import com.ysstech.common.util.verifyutil.VerifyImage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@Slf4j
@Api(tags = "验证码生成api")
@RequestMapping(value = "/code")
public class CodeController extends BaseController {

    @ApiOperation(value = "获取登录验证码")
    @YssLog(module = "系统管理", remark = "获取登录验证码")
    @RequestMapping("/getSessioniCode")
    public void getSessioniCode(HttpServletResponse response, String type) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");
        //验证码
        int codetype = YssCodeEnum.FOURE.getCode(), length = 4;
        if ("1".equals(type) || "2".equals(type)) {
            length = 6;
            codetype = Integer.valueOf(type);
        }
        VerifyCodeInfo verifyCode = VerifyCode.generateVerifyCode(codetype);
        Session session=SecurityUtils.getSubject().getSession();
        session.setAttribute("verifyCode", verifyCode);
        //session.setAttribute("verifyCode", verifyCode.verifyCode);
       // session.setAttribute("expireTime", verifyCode.expireTime);
        //背景图
        BufferedImage image = VerifyImage.getVerifyImage(verifyCode.verifyCode, length);
        //输出
        ImageIO.write(image, "PNG", response.getOutputStream());
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        // flush it in the response
        ServletOutputStream responseOutputStream = null;
        responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
